package com.aliyun.product.server.service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 数据库初始化器
 *
 * 
 * @date 2024/12/04
 */
@Slf4j
@Component
public class DatabaseInitializer {

    private static final String TECH_SOLUTION_PRODUCT = "tech_solution_product";
    private static final String DB_INIT_SCRIPT_SQL = "db-init-script.sql";

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init() throws Exception {
        try (Connection conn = dataSource.getConnection()) {
            //表已经存在，无需执行数据库初始化脚本
            if (tableExists(conn, TECH_SOLUTION_PRODUCT)) {
                log.info("table already exists, skip database initialization.");
                return;
            }
            log.info("start to initialize database.");
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setAutoCommit(true);
            runner.setStopOnError(true);
            runner.runScript(Resources.getResourceAsReader(DB_INIT_SCRIPT_SQL));
            log.info("database initialization finished.");
        }
    }

    /**
     * Table 存在
     *
     * @param connection 连接
     * @param tableName  表名称
     * @return boolean
     * @throws SQLException sql异常
     */
    private boolean tableExists(Connection connection, String tableName) throws SQLException {
        DatabaseMetaData meta = connection.getMetaData();
        ResultSet resultSet = meta.getTables(null, null, tableName, new String[] {"TABLE"});
        return resultSet.next();
    }
}